/**
 * \file ServerService.java
 * \author Nicolaj Quottrup
 */
package com.rootbat.fleamarketapp.authorization;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.http.NameValuePair;

import com.rootbat.fleamarketapp.utilities.HttpToolkit;
import com.rootbat.fleamarketapp.utilities.IHttpToolkit.EHTTP_TYPE;
import com.rootbat.fleamarketapp.utilities.JsonResult;

import android.app.ProgressDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;

/**
* \brief Class to make calls to RESTful service that can be bound from activity
*/
public class ServerService extends Service{
	// Binder object for activity
    private final IBinder mBinder = new LocalBinder();
    // Hashmap to store sults in
    private Map<String, JsonResult<Object>> result = new ConcurrentHashMap<String, JsonResult<Object>>();
    // Broadcast receiver to respond to
    public static final String RECEIVER = "com.rootbat.server_receiver";
    Context xt = null;
    
    /// <summary>
    /// Request - Converts function parameters to class object, gives the context from parameter to asynctast (for ProgressBar, must be activity), and then starts asynctask request
    /// </summary>
    public void Request(Context ctx, String _key,String _host, String _controller, String _action, EHTTP_TYPE _method, List<NameValuePair> _nameValuePairs, Type _objectType) {
        // Convert parameters to class object
    	ServerArguments servArg = new ServerArguments(_key, _host, _controller, _action, _method, _nameValuePairs, _objectType);
    	// Give activity context to asynctast
        WebTask task = new WebTask(ctx);
        // Start asynctask request
        task.execute(servArg);
    }

    /// <summary>
    /// getResult - gets the result from hashmap depending on key.
    /// </summary>
    public JsonResult<Object> getResult(String key)
    {
    	return result.get(key);
    }
    
    /// <summary>
    /// onBind - returns binder object to binder.
    /// </summary>
    @Override
    public IBinder onBind(Intent arg0)
    {
        return mBinder;
    }
    
    /// <summary>
    /// LocalBinder - Class that activity calls to get service instance
    /// </summary>
    public class LocalBinder extends Binder {
	    /// <summary>
	    /// getService - returns this instance
	    /// </summary>
        public ServerService getService() {
            return ServerService.this;
        }
    }
    
    /// <summary>
    /// WebTask - AsyncTask, runs in a different task, makes progressdialog on start, performs background work, then disables progressdialog at end
    /// </summary>
    private class WebTask extends AsyncTask<ServerArguments, Void, Void> {
    	// ProgressDialog object holder
    	private ProgressDialog dialog = null;
    	// AsyncTask context for ProgressDialog
        private Context context = null;
        
        /// <summary>
        /// WebTask - Creates progressdialog from context.
        /// </summary>
    	private WebTask(Context ctx)
    	{
                context = ctx;
                dialog = new ProgressDialog(context);
    	}
    	
        /// <summary>
        /// onPreExecute - Sets progressdialog's title and message and shows it on UI.
        /// </summary>
        @Override
        protected void onPreExecute() {
                dialog.setTitle("Please wait");
                dialog.setMessage("Working...");
                dialog.setCancelable(false);
                dialog.show();
        }
    	
        /// <summary>
        /// doInBackground - Makes HTTP call with serverarguments to server and parses respond, then puts it in hashtable depending on argument key, then sends broadcast out that its done and with what key
        /// </summary>
    	@Override
    	protected Void doInBackground(ServerArguments... params) {
        	
    		// Get start parameters
            ServerArguments servArg = params[0];

            // Make http call from arguments, then get results
            JsonResult<Object> res = HttpToolkit.getInstance().httpCall(servArg.Host, servArg.Controller, servArg.Action, servArg.Method, servArg.NameValuePairs, servArg.ObjectType);
            
            // Put results into hashtable
            result.put(servArg.Key, res);
            
            // Send broadcast with key for call
            Intent intent = new Intent();
            intent.putExtra("Action", servArg.Key);
            intent.setAction(RECEIVER);
            sendBroadcast(intent);
            return null;
        }
    	
        /// <summary>
        /// onPostExecute - closes progressbar dialog
        /// </summary>
        @Override
        protected void onPostExecute(Void res) {
                dialog.dismiss(); 
        }
        
    }
}
